import {
  ModalForm,
  ProForm,
  ProFormText,
} from '@ant-design/pro-components';
import { message, Checkbox, Collapse, Space, Input } from 'antd';
import { api } from '@/services/api';
import type { Group, Permission } from '@/services/generated/models';
import { GroupRequest } from '@/services/generated';
import { useState, useEffect } from 'react';

interface RoleFormProps {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSuccess: () => void;
  role?: Group;
}

interface GroupedPermissions {
  [key: string]: {
    [key: string]: Permission[];
  };
}

const { Panel } = Collapse;

const RoleForm: React.FC<RoleFormProps> = ({
  visible,
  onVisibleChange,
  onSuccess,
  role,
}) => {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [groupedPermissions, setGroupedPermissions] = useState<GroupedPermissions>({});
  const [searchText, setSearchText] = useState('');
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);

  // 获取权限列表
  useEffect(() => {
    const fetchPermissions = async () => {
      try {
        const permissionList = await api.accounts.accountsPermissionsList({});
        setPermissions(permissionList);

        // 按应用和模型分组
        const grouped: GroupedPermissions = {};
        permissionList.forEach((perm) => {
          if (!grouped[perm.appLabel]) {
            grouped[perm.appLabel] = {};
          }
          if (!grouped[perm.appLabel][perm.model]) {
            grouped[perm.appLabel][perm.model] = [];
          }
          grouped[perm.appLabel][perm.model].push(perm);
        });
        setGroupedPermissions(grouped);

        // 如果是编辑模式，设置已选权限
        if (role?.permissions) {
          setSelectedPermissions(role.permissions);
        }
      } catch (error) {
        console.error('获取权限列表失败:', error);
        message.error('获取权限列表失败');
      }
    };

    if (visible) {
      fetchPermissions();
    }
  }, [visible, role]);

  const handlePermissionChange = (permId: number, checked: boolean) => {
    setSelectedPermissions(prev => {
      if (checked) {
        return [...prev, permId];
      } else {
        return prev.filter(id => id !== permId);
      }
    });
  };

  const handleModelSelectAll = (appLabel: string, model: string, perms: Permission[], checked: boolean) => {
    setSelectedPermissions(prev => {
      const otherPerms = prev.filter(id => !perms.find(p => p.id === id));
      if (checked) {
        return [...otherPerms, ...perms.map(p => p.id)];
      }
      return otherPerms;
    });
  };

  const isModelAllSelected = (perms: Permission[]) => {
    return perms.every(perm => selectedPermissions.includes(perm.id));
  };

  const isModelPartiallySelected = (perms: Permission[]) => {
    return perms.some(perm => selectedPermissions.includes(perm.id)) && !isModelAllSelected(perms);
  };

  const filterPermissions = (perm: Permission) => {
    if (!searchText) return true;
    return (
      perm.name.toLowerCase().includes(searchText.toLowerCase()) ||
      perm.codename.toLowerCase().includes(searchText.toLowerCase())
    );
  };

  return visible ? (
    <ModalForm
      title={role ? '编辑角色' : '新建角色'}
      visible={visible}
      onVisibleChange={onVisibleChange}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        width: 800,
      }}
      initialValues={{
        ...role,
        permissions: selectedPermissions,
      }}
      onFinish={async (values: GroupRequest) => {
        try {
          const submitData = {
            ...values,
            permissions: selectedPermissions,
          };
          if (role) {
            // 更新角色
            await api.accounts.accountsGroupsPartialUpdate({
              id: role.id,
              patchedGroupRequest: submitData,
            });
            message.success('更新成功');
          } else {
            // 创建新角色
            await api.accounts.accountsGroupsCreate({
              groupRequest: submitData,
            });
            message.success('创建成功');
          }
          onSuccess();
          return true;
        } catch (error) {
          message.error(role ? '更新失败' : '创建失败');
          return false;
        }
      }}
    >
      <ProFormText
        name="name"
        label="角色名称"
        placeholder="请输入角色名称"
        rules={[
          {
            required: true,
            message: '角色名称不能为空',
          },
        ]}
      />
      <ProForm.Item
        label="权限配置"
        name="permissions"
        trigger="onValuesChange"
      >
        <div>
          <Input.Search
            placeholder="搜索权限"
            style={{ marginBottom: 16 }}
            onChange={e => setSearchText(e.target.value)}
          />
          <Collapse defaultActiveKey={Object.keys(groupedPermissions)}>
            {Object.entries(groupedPermissions).map(([appLabel, models]) => (
              <Panel header={appLabel} key={appLabel}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  {Object.entries(models).map(([model, perms]) => {
                    const filteredPerms = perms.filter(filterPermissions);
                    if (filteredPerms.length === 0) return null;
                    
                    return (
                      <div key={`${appLabel}-${model}`} style={{ marginBottom: 8 }}>
                        <Checkbox
                          indeterminate={isModelPartiallySelected(filteredPerms)}
                          checked={isModelAllSelected(filteredPerms)}
                          onChange={(e) => handleModelSelectAll(appLabel, model, filteredPerms, e.target.checked)}
                        >
                          <b>{model}</b>
                        </Checkbox>
                        <div style={{ marginLeft: 24, marginTop: 8 }}>
                          {filteredPerms.map(perm => (
                            <div key={perm.id}>
                              <Checkbox
                                checked={selectedPermissions.includes(perm.id)}
                                onChange={(e) => handlePermissionChange(perm.id, e.target.checked)}
                              >
                                {perm.name}
                              </Checkbox>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })}
                </Space>
              </Panel>
            ))}
          </Collapse>
        </div>
      </ProForm.Item>
    </ModalForm>
  ) : null;
};

export default RoleForm;
